//
//  AddBowenViewController.m
//  YiqiMobile
//
//  Created by henry on 13-5-4.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "EditBowenViewController.h"
#import "Utility.h"
#import "Utility.h"
#import "Config.h"
#import "QuartzCore/QuartzCore.h"
#import "CustomNavigationController.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "DefineAction.h"

@interface EditBowenViewController ()

@end

@implementation EditBowenViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIImageView *backgroundimageView=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,220)];
        backgroundimageView.userInteractionEnabled=YES;
        UIImage *image=[Utility imageNamed:@"cg_bg2.png"];
        UIEdgeInsets insets=UIEdgeInsetsMake(10, 0, 50, 0);
        if ([[[UIDevice currentDevice] systemVersion] floatValue]<6.0) {
            image=[image resizableImageWithCapInsets:insets];
        }else{
            image=[image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        }
        backgroundimageView.image=image;
        [self.view addSubview:backgroundimageView];
        
        //标题
        self.sorcebiaotilabel=[Utility detailTextLabel:CGRectMake(15, 8, 300, 17) andFontSize:15];
        [self.view addSubview: self.sorcebiaotilabel];
        UIImageView *titleinputBg=[[UIImageView alloc] initWithFrame:CGRectMake(8, 30, 304, 44)];
        titleinputBg.userInteractionEnabled=YES;
        titleinputBg.image=[Utility imageNamed:@"biaoti_title.png"];
        [self.view addSubview:titleinputBg];
        self.titleField = [self customTextField:CGRectMake(6, 3, 262, 37)];
        self.titleField.placeholder=@"输入博文标题";
        self.titleField.delegate=self;
        [titleinputBg
         addSubview:self.titleField];
        
        
        UIImageView *contentFieldbg=[[UIImageView alloc] initWithFrame: CGRectMake(8, 78, 304, 97)];
        contentFieldbg.userInteractionEnabled=YES;
        contentFieldbg.image=[Utility imageNamed:@"biaoti_content.png"];
        [self.view addSubview:contentFieldbg];
        
        
        self.contentField=[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 304, 90)];
        self.contentField.text=@"简介";
        self.contentField.backgroundColor=[UIColor  clearColor];
        //self.contentField.layer.cornerRadius = 8;//设置那个圆角的有多圆
        self.contentField.layer.borderWidth = 0;//设置边框的宽度，当然可以不要
        //self.contentField.layer.borderColor = [[UIColor blackColor] CGColor];//设置边框的颜色
        self.contentField.keyboardType=UIKeyboardTypeDefault;
        self.contentField.layer.masksToBounds = YES;//设为NO去试试
        self.contentField.autocorrectionType=UITextAutocorrectionTypeNo;
        self.contentField.returnKeyType=UIReturnKeyDone;
        self.contentField.textColor=[UIColor lightGrayColor];
        self.contentField.font=[UIFont fontWithName:FONT_FAMILY size:15.0];
        self.contentField.enablesReturnKeyAutomatically=YES;
        self.contentField.delegate=self;
        [contentFieldbg addSubview:self.contentField];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.titleView=[Utility getTitleView:@"编辑标题/简介"];
   
    
    
    //显示隐藏博文简介
    [self.view addSubview:[Utility customButton:self action:@selector(showorhideAction:) normalImage:@"biaoti_showcontent.png" lightedImage:@"biaoti_showcontent.png" frame:CGRectMake(230, 178, 75, 22) title:nil tag:0]];
    
    
    //确定按钮
    [self.view addSubview:[Utility customButton:self action:@selector(onclickButtonAction:) normalImage:@"biaoti_ok_normal.png" lightedImage:@"biaoti_ok_hover.png" frame:CGRectMake(10, 240, 300, 50) title:nil tag:100]];
    //取消按钮
    [self.view addSubview:[Utility customButton:self action:@selector(onclickButtonAction:) normalImage:@"biaoti_cannel_normal.png" lightedImage:@"biaoti_cannel_hover@2x.png" frame:CGRectMake(10, 300, 300, 50) title:nil tag:101]];
    
	// Do any additional setup after loading the view.
}
-(void) showData:(NSDictionary*) dict{
    self.caogaoDict=dict;
    self.sorcebiaotilabel.text=[NSString stringWithFormat:@"初始标题：%@",[dict objectForKey:@"str3"]];
    if (![[dict objectForKey:@"str2"] isEqualToString:@""]) {
        self.titleField.text=[dict objectForKey:@"str2"];
    }
    self.contentField.text=[dict objectForKey:@"str6"];
    self.contentField.textColor=[UIColor blackColor];
}

-(IBAction) onclickButtonAction:(id)sender{
   
    if ([sender tag]==100) {
        NSString *title=self.titleField.text;
        if (title==nil||[title isEqualToString:@""]) {
            [Utility customAlertWithMsg:@"请输入博文标题" andTitle:ALRRTTITLE andDelagate:nil];
            return;
        }
        NSLog(@"确定");
    }else if ([sender tag]==101) {
        [self.navigationController  popViewControllerAnimated:YES];
    }
}


//保存博文
-(void) savebowenwithType:(int) type andContent:(NSString*)ggcontent{
    NSString *title=self.titleField.text;
    NSString *content=self.contentField.text;
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
   
    NSString *url=[NSString stringWithFormat:@"%@/%@?type=0",[Utility  getServerUrl],CREATEBIAOTIACTION];
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    param[@"b.b1"]=title;//博文标题
    param[@"b.u0"]=userId;//标题创建人
    param[@"b.e0"]=[self.caogaoDict objectForKey:@"str1"];//所属圈子
    param[@"b.b4"]=content;//简介
    param[@"b.b6"]=@"";//标签
    param[@"b.wt0"]=@"1";//所属网站分类
    if (ggcontent.length>0) {//是否同时新增一个供稿 0 是(那么下面参数需要)  1否
        param[@"type"]=@"0";//是否同时新增一个供稿 0 是(那么下面参数需要)  1否
        param[@"g.t0"]=@(type);//供稿内容类型
        param[@"g.g2"]=ggcontent;//供稿内容（文字）
    }else{
          param[@"type"]=@"1";
    }
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
    [self.request startLoadData];
}
- (void)requestFinished:(id)context{
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            
            if ([[result objectForKey:@"method"] isEqualToString:CREATEBIAOTIACTION]) {
                NSLog(@"%@",@"createB");
                UIViewController *viewController=[[self.navigationController viewControllers] objectAtIndex:0];
                if ([viewController respondsToSelector:@selector(loadDataFromServer)]) {
                    [viewController performSelector:@selector(loadDataFromServer) withObject:nil];
                    [self.navigationController  popToViewController:viewController animated:YES];
                }
                
            }
            
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}


-(void) showorhideAction:(UIButton*) sender{
    NSLog(@"%@",@"显示或者隐藏简介");
}


- (BOOL) textViewShouldBeginEditing:(UITextView *)textView{
    self.contentField.textColor=[UIColor blackColor];
    self.contentField.text = @"";
    return YES;
}
-(void) textViewDidChange:(UITextView *)textView{
    if(self.contentField.text.length == 0){
        self.contentField.textColor = [UIColor lightGrayColor];
        self.contentField.text = @"简介";
        [self.contentField resignFirstResponder];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    if ([text isEqualToString:@"\n"]) {//按下return键
        [self.contentField resignFirstResponder];
        return NO;
    }else {
        if ([textView.text length] < 140) {//判断字符个数
            return YES;
        }
    }
    return NO;
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.titleField) {
        if (self.titleField.text.length>0) {
            [self.contentField becomeFirstResponder];
            return YES;
        }
    }
    return NO;
}



-(UITextField*) customTextField:(CGRect) frame{
    
    UITextField *textFied = [[UITextField alloc] initWithFrame:frame];
    textFied.keyboardType=UIKeyboardAppearanceDefault;
    textFied.autocorrectionType = UITextAutocorrectionTypeNo;
    textFied.returnKeyType=UIReturnKeyNext;
    textFied.clearButtonMode=UITextFieldViewModeWhileEditing;
    textFied.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    textFied.backgroundColor=[UIColor  clearColor];
    textFied.borderStyle=UITextBorderStyleNone;
    textFied.textColor=[UIColor blackColor];
    textFied.font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    textFied.autocorrectionType=UITextAutocorrectionTypeNo;
    [textFied setBorderStyle:UITextBorderStyleNone];
    textFied.returnKeyType = UIReturnKeyDone;
    textFied.keyboardType=UIKeyboardTypeDefault;
    return textFied;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
